﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using XChipTool.Enties;
using XChipUtils;

namespace XCSerialPort
{
    public class Pageactions : IPageactions
    {
        ISerialPortManager serialPort;
        IBitsHelper bitsHelper;

        public Pageactions()
        {
            this.serialPort = XCSerialPort.NavigationService.GetSerialPort();
            bitsHelper = new BitsHelp();
        }

        public Pageactions(ISerialPortManager serialPort)
        {
            this.serialPort = serialPort;
            bitsHelper = new BitsHelp();
        }

        private string GetControlName(object sender)
        {
            if (sender is TextBox textBox)
            {
                return textBox.Name;
            }
            else if (sender is CheckBox checkBox)
            {
                return checkBox.Name;
            }
            else if (sender is ComboBox comboBox)
            {
                return comboBox.Name; // 可以添加对 ComboBox 的支持
            }
            else if (sender is RadioButton radioButton)
            {
                return radioButton.Name; // 可以添加对 RadioButton 的支持
            }
            else if (sender is System.Windows.FrameworkElement element) // FrameworkElement 可以处理更多控件
            {
                return element.Name; // 直接使用控件的 Name 属性
            }
            else if (!string.IsNullOrEmpty(sender.ToString()))
            {
                return sender.ToString();
            }
            return string.Empty;
        }

        public string PageAddrSet(object sender, object _Val, List<addressregister> listaddSum, string ModeName = null)
        {
            string controlName = GetControlName(sender);
            if (string.IsNullOrEmpty(controlName)) return "";

            
            var listSum = GetMatchingRegisters(controlName, listaddSum, ModeName);
            List<addressregister> listadd = new List<addressregister>();

            // 如果只有一个匹配的寄存器，直接写入
            if (listSum.Count == 1)
            {
                var reg = listSum[0];
                ulong address = Convert.ToUInt64(reg.Address, 16);

                //// 获取控件文本值
                //string textValue = "";
                //if (sender is TextBox textBox)
                //{
                //    textValue = textBox.Text;
                //}

                var val = bitsHelper.SetBitsToUint(reg.Bits, reg.Hex, _Val.ToString());
                string msg;

                serialPort.WriteRegister(address, new List<ulong> { val }, out msg);

                if (!string.IsNullOrEmpty(msg))
                {
                    EventAggregator.Publish(new LogMessage { Message = $"设置寄存器 0x{address:X4} 失败: {msg}" });
                    return $"0x{reg.Address}失败: {msg}";
                }
                else
                {
                    EventAggregator.Publish(new LogMessage
                    {
                        Message = $"W:0x{address:X4},0x{val:X2}"
                    });
                    return "";
                }
            }
            else
            {
                // 处理多个寄存器的情况
                var targetList = (listadd.Count > 0 && !string.IsNullOrEmpty(ModeName)) ? listadd : listSum;
                string[] suffixes = { "_h", "_m1", "_m0", "_l", "" };
                StringBuilder resultBuilder = new StringBuilder();
                string msg = "";
                bool hasError = false;

                foreach (var suffix in suffixes)
                {
                    string registerName = string.IsNullOrEmpty(ModeName) ?
                        controlName + suffix :
                        controlName + suffix + "_" + ModeName;

                    var reg = targetList.FirstOrDefault(c =>
                        c.NameType.Equals(registerName, StringComparison.OrdinalIgnoreCase));

                    if (reg != null)
                    {
                        ulong address = Convert.ToUInt64(reg.Address, 16);

                        // 获取控件文本值
                        string textValue = "";
                        if (sender is TextBox textBox)
                        {
                            textValue = textBox.Text;
                        }

                        var val = bitsHelper.SetBitsToUint(reg.Bits, reg.Hex, textValue);

                        serialPort.WriteRegister(address, new List<ulong> { val }, out msg);

                        if (!string.IsNullOrEmpty(msg))
                        {
                            hasError = true;
                            resultBuilder.Append($"0x{reg.Address}失败: {msg}; ");
                        }
                        else
                        {
                            EventAggregator.Publish(new LogMessage
                            {
                                Message = $"W:0x{address:X4},0x{val:X2}"
                            });
                        }
                    }
                }

                if (hasError)
                {
                    EventAggregator.Publish(new LogMessage { Message = $"设置 {controlName} 时发生错误: {resultBuilder}" });
                    return resultBuilder.ToString();
                }

                return "";
            }
        }

        public string PageAddrGet(object sender, List<addressregister> listaddSum, string ModeName = null)
        {
            string controlName = GetControlName(sender);
            if (string.IsNullOrEmpty(controlName)) return "";
            List<addressregister> listadd = new List<addressregister>();
            var listSum = GetMatchingRegisters(controlName, listaddSum, ModeName);

            if (listSum.Count ==1)
            {
                ulong address = Convert.ToUInt64(listSum[0].Address, 16);
                string msg;
                var values = serialPort.ReadRegister(address, out msg, 1);

                if (values != null && values.Count > 0 && string.IsNullOrEmpty(msg))
                {
                   
                    string val = bitsHelper.GetBitsToUint(listSum[0].Bits, listSum[0].Hex, values[0].ToString("X")).ToString("X");
                    EventAggregator.Publish(new LogMessage
                    {
                        Message = $"R:0x{address:X4},0x{val}"
                    });
                    return val;
                }
                else
                {
                    EventAggregator.Publish(new LogMessage
                    {
                        Message = $"读取寄存器 0x{address:X4} 失败: {msg}"
                    });
                    return "FF";
                }
            }
            else
            {
                var targetList = (listadd.Count > 0 && !string.IsNullOrEmpty(ModeName)) ? listadd : listSum;
                string[] suffixes = { "_h", "_m1", "_m0", "_l", "" };
                string Val = "";
                bool success = true;
                List<string> errors = new List<string>();
                string msg = "";

                foreach (var suffix in suffixes)
                {
                    string registerName = string.IsNullOrEmpty(ModeName) ?
                        controlName + suffix :
                        controlName + suffix + "_" + ModeName;

                    addressregister reg = null;
                    if (suffix == "_h" || suffix == "_l")
                    {
                        reg = targetList.FirstOrDefault(c =>
                            c.NameType.Equals(registerName, StringComparison.OrdinalIgnoreCase));

                        if (reg == null)
                        {
                            if (suffix == "_h")
                            {
                                var hRegs = targetList.Where(c => c.NameType.ToLower().Contains("_h")).ToList();
                                if (hRegs.Any())
                                {
                                    var exactEndReg = hRegs.FirstOrDefault(c => c.NameType.ToLower().EndsWith("_h"));
                                    reg = exactEndReg ?? hRegs.Last();
                                }
                            }
                            else if (suffix == "_l")
                            {
                                var lRegs = targetList.Where(c => c.NameType.ToLower().Contains("_l") && !c.NameType.ToLower().Contains("_long")).ToList();
                                if (lRegs.Any())
                                {
                                    var exactEndReg = lRegs.FirstOrDefault(c => c.NameType.ToLower().EndsWith("_l"));
                                    reg = exactEndReg ?? lRegs.Last();
                                }
                            }
                        }
                    }
                    else
                    {
                        reg = targetList.FirstOrDefault(c =>
                            c.NameType.Equals(registerName, StringComparison.OrdinalIgnoreCase));
                    }

                    if (reg != null)
                    {
                        ulong address = Convert.ToUInt64(reg.Address, 16);
                        var values = serialPort.ReadRegister(address, out msg, 1);

                        if (values != null && values.Count > 0)
                        {
                            Val += values[0].ToString("X2");
                            EventAggregator.Publish(new LogMessage
                            {
                                Message = $"R:{address:X},0x{Val}"
                            });
                        }
                        else
                        {
                            success = false;
                            errors.Add($"0x{address:X}: {msg}");
                            Val += "00";
                        }
                    }
                }

                if (success)
                {
                    if (string.IsNullOrEmpty(Val))
                    {
                        EventAggregator.Publish(new LogMessage
                        {
                            Message = $"ERROR 读取 {controlName}: 未找到相关寄存器"
                        });
                        return "FF";
                    }

                    return Val;
                }
                else
                {
                    EventAggregator.Publish(new LogMessage
                    {
                        Message = $"读取 {controlName} 错误: {string.Join("; ", errors)}"
                    });
                    return "FF";
                }
            }
              
            
          
        }

        // 获取匹配的寄存器
        private List<addressregister> GetMatchingRegisters(string controlName, List<addressregister> listaddSum, string ModeName)
        {
            var listSum = listaddSum.Where(c => c.NameType.ToLower().Contains(controlName.ToLower())).ToList();

            if (string.IsNullOrEmpty(ModeName))
            {
                var exactMatch = listaddSum.Where(c => c.NameType.Equals(controlName, StringComparison.OrdinalIgnoreCase)).ToList();
                return exactMatch.Count > 0 ? exactMatch : listSum;
            }
            else
            {
                return listSum.Where(c => c.NameType.ToLower().Contains(ModeName.ToLower())).ToList();
            }
        }

        public string PageCheckSet(object sender, List<addressregister> listaddSum, string ModeName = null)
        {
            string controlName = GetControlName(sender);
            if (string.IsNullOrEmpty(controlName)) return "";
            var isChecked = false;
            System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
            {
                if (sender is CheckBox checkBox)
                {
                    isChecked = (bool)(sender as CheckBox).IsChecked;
                }
            });
            
            List<addressregister> listadd = new List<addressregister>();
            var listSum = GetMatchingRegisters(controlName, listaddSum, ModeName);


            var targetList = (listadd.Count > 0 && !string.IsNullOrEmpty(ModeName)) ? listadd : listSum;
            string msg = "";

            var regList = targetList.Where(c => c.ControlType == "1").ToList();

            if (regList.Count == 1)
            {
                var reg = regList[0];
                ulong address = Convert.ToUInt64(reg.Address, 16);
                var currentValues = serialPort.ReadRegister(address, out msg, 1);

                if (currentValues != null && currentValues.Count > 0 && string.IsNullOrEmpty(msg))
                {
                    string currentValueHex = currentValues[0].ToString("X2");
                    ulong newValue = bitsHelper.SetBitsCheckedToUint(
                        reg.Bits,
                        reg.Hex,
                        currentValueHex,
                        isChecked == true);

                    serialPort.WriteRegister(address, new List<ulong> { newValue }, out msg);

                    if (string.IsNullOrEmpty(msg))
                    {
                        EventAggregator.Publish(new LogMessage
                        {
                            Message = $"W:0x{address:X4},0x{newValue:X2}"
                        });
                        return "";
                    }
                    else
                    {
                        EventAggregator.Publish(new LogMessage
                        {
                            Message = $"设置 {controlName} 错误: {msg}"
                        });
                        return $"设置 {controlName} 失败: {msg}";
                    }
                }
                else
                {
                    EventAggregator.Publish(new LogMessage
                    {
                        Message = $"设置 {controlName} 错误: 读取当前值失败: {msg}"
                    });
                    return $"设置 {controlName} 错误: 读取当前值失败: {msg}";
                }
            }
            else
            {
                EventAggregator.Publish(new LogMessage
                {
                    Message = $"设置 {controlName} 错误: 未找到对应的寄存器配置"
                });
                return $"设置 {controlName} 错误: 未找到对应的寄存器配置";
            }
        }

        public string PageCheckGet(object sender, List<addressregister> listaddSum, string ModeName = null)
        {
            string controlName = GetControlName(sender);
            if (string.IsNullOrEmpty(controlName)) return "";

            IBitsHelper bitsHelper = new BitsHelp();
            
            List<addressregister> listadd = new List<addressregister>();
            var listSum = GetMatchingRegisters(controlName, listaddSum, ModeName);
          

            var targetList = (listadd.Count > 0 && !string.IsNullOrEmpty(ModeName)) ? listadd : listSum;
            string msg = "";

            var regList = targetList.Where(c => c.ControlType == "1").ToList();

            if (regList.Count == 1)
            {
                var reg = regList[0];
                ulong address = Convert.ToUInt64(reg.Address, 16);
                var values = serialPort.ReadRegister(address, out msg, 1);

                if (values != null && values.Count > 0 && string.IsNullOrEmpty(msg))
                {
                    bool isChecked = bitsHelper.GetBitsCheckedToBool(reg.Bits, reg.Hex, values[0].ToString("X")) == 0;
                    // 确保 sender 是 CheckBox，并且不为 null
                    var checkBox = sender as CheckBox;
                    if (checkBox != null)
                    {
                        // 使用 Dispatcher 更新 UI
                        System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
                        {
                            checkBox.IsChecked = isChecked;
                        });
                    }
                    else
                    {
                        // 如果 sender 不是 CheckBox，记录日志或处理错误
                        EventAggregator.Publish(new LogMessage
                        {
                            Message = "Warning: sender 不是 CheckBox"
                        });
                    }
                    EventAggregator.Publish(new LogMessage
                    {
                        Message = $"R:0x{address:X4},0x{values[0]:X2}"
                    });

                    return "";
                }
                else
                {
                    EventAggregator.Publish(new LogMessage
                    {
                        Message = $"读取 {controlName} 错误: {msg}"
                    });
                    return $"读取 {controlName} 错误: {msg}";
                }
            }
            else
            {
                EventAggregator.Publish(new LogMessage
                {
                    Message = $"读取 {controlName} 错误: 未找到对应的寄存器配置"
                });
                return $"读取 {controlName} 错误: 未找到对应的寄存器配置";
            }
        }

        public List<ulong> ReadRegister(ulong address, out string msg, int count)
        {
            var result = serialPort.ReadRegister(address, out msg, count);

            if (string.IsNullOrEmpty(msg) && result != null && result.Count > 0)
            {
                // 读取操作，记录读取的值
                EventAggregator.Publish(new LogMessage { Message = $"R:0x{address:X},0x{result[0]:X}" });
            }

            return result;
        }

        public void WriteRegister(ulong address, List<ulong> values, out string msg)
        {
            serialPort.WriteRegister(address, values, out msg);

            if (string.IsNullOrEmpty(msg) && values != null && values.Count > 0)
            {
                // 写入操作，记录写入的值
                EventAggregator.Publish(new LogMessage { Message = $"W:0x{address:X},0x{values[0]:X}" });
            }
        }
    }
}